<?php
//
//  Fish
//
//  Created by Elliot Yap on 2011-09-06.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

class Fish {

	public static function xr($arr,$key) {
		return $arr[$key];
	}
	
	# yii session
	public static function sAdd($key,$aval,$akey=null) {
		if (!isset(Yii::app()->session[$key])) 
			Yii::app()->session[$key] = array();
		if (!is_array(Yii::app()->session[$key]))
			Yii::app()->session[$key] = array();
		$rs = Yii::app()->session[$key];
		if ($akey!==null) 
			$rs[$akey] = $aval;
		else
			$rs[] = $aval;
		Yii::app()->session[$key] = $rs;
	}
	public static function sSet($key,$aval) {
		Yii::app()->session[$key] = $aval;
	}
	public static function sDel($key,$akey=null) {
		if ($akey===null) {
			unset(Yii::app()->session[$key]);
		} else {
			$rs = Yii::app()->session[$key];
			unset($rs[$akey]);
			Yii::app()->session[$key] = $rs;
		}
	}
	public static function sHas($key,$akey=null) {
		if (isset(Yii::app()->session[$key]) ) {
			if ($akey===null) {
				return true;
			} else {
				return isset(Yii::app()->session[$key][$akey]);
			}
		}
		return false;
	}
	
	public static function getRow($table,$id,$flush=false){
		
		if (!empty($id)) {
			$result = self::__getSessionOrDb($table,$flush);
			if (isset($result[$id])) {
				return $result[$id];
			}
			return false;
		}
		return false;
	}
	
	public static function getList($table,$valcol,$flush=false,$default='-SELECT-'){
		
		$result = self::__getSessionOrDb($table,$flush);
		$list = array(''=>$default);
		foreach ($result as $key => $row) $list[$row['id']] = $row[$valcol];
		return $list;
	}
	
	public static function getListDetails($table,$flush=false){
		
		$result = self::__getSessionOrDb($table,$flush);
		foreach ($result as $key => $row) $list[$row['id']] = $row;
		return $list;
	}

	
	private static function __getSessionOrDb($table,$flush) {
		#$flush = true;
		$result = Yii::app()->session->get($table.'list');
		if ( empty($result) || $flush ) {
			$result = array();
			$rs = Yii::app()->db->createCommand('SELECT * FROM '.$table)->queryAll();
			foreach ($rs as $row) {
				$result[$row['id']] = $row;
			}
			Yii::app()->session->add($table.'list',$result);
		}
		return $result;
	}
}